﻿using BlossomiShymae.GrrrLCU;
using DryIoc;
using HandyControl.Controls;
using ImTools;
using LOLApi;
using LOLApi.Models;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using Tryit.Views;


namespace Tryit.ViewModels
{
    public class SummonerInfoViewModel : BindableBase, INavigationAware
    {
        #region 变量
        private IRegionManager _regionManager;
        public static Summoner Summoner { get; set; } = new Summoner();

        private string _showLoading = "Hidden";
        public string ShowLoading
        {
            get
            {
                return _showLoading;
            }
            set { SetProperty(ref _showLoading, value); }
        }
        private string _showGrid = "Hidden";
        public string ShowGrid
        {
            get { return _showGrid; }
            set { SetProperty(ref _showGrid, value); }
        }
        /// <summary>
        /// 排位数据
        /// </summary>
        private Rank _rank;
        public Rank Rank
        {
            get { return _rank; }
            set { SetProperty(ref _rank, value); }
        }
        /// <summary>
        /// 经验值
        /// </summary>
        private string _eXP;
        public string EXP
        {
            get { return _eXP; }
            set { SetProperty(ref _eXP, value); }
        }

        /// <summary>
        /// 拥有的英雄数量
        /// </summary>
        private string _championCount = "";
        public string ChampionCount
        {
            get { return _championCount; }
            set { SetProperty(ref _championCount, value); }
        }
        /// <summary>
        /// 拥有的皮肤数量
        /// </summary>
        private string _skinsCount = "";
        public string SkinsCount
        {
            get { return _skinsCount; }
            set { SetProperty(ref _skinsCount, value); }
        }
        /// <summary>
        /// 头像
        /// </summary>
        private ImageSource _avatar;
        public ImageSource Avatar
        {
            get { return _avatar; }
            set { SetProperty(ref _avatar, value); }
        }
        /// <summary>
        /// 游戏等级
        /// </summary>
        private string _summonerLevel;
        public string SummonerLevel
        {
            get { return _summonerLevel; }
            set { SetProperty(ref _summonerLevel, value); }
        }
        /// <summary>
        /// 召唤师名称
        /// </summary>
        private string _nickName;
        public string NickName
        {
            get { return _nickName; }
            set { SetProperty(ref _nickName, value); }
        }
        /// <summary>
        /// 复制昵称
        /// </summary>
        public DelegateCommand SuccessCmd { get => new DelegateCommand(CopyName); }
        /// <summary>
        /// 表格数据
        /// </summary>
        public ObservableCollection<Recordby20> DataList { get; set; } = new ObservableCollection<Recordby20>();
        public ObservableCollection<ImageSource> OwnedChampionsImage { get; set; } = new ObservableCollection<ImageSource>();
        public ObservableCollection<ImageSource> OwnedSkinsImage { get; set; } = new ObservableCollection<ImageSource>();
        public ObservableCollection<ImageSource> OwnedChampionsImageAll { get; set; } = new ObservableCollection<ImageSource>();
        public ObservableCollection<ImageSource> OwnedSkinsImageAll { get; set; } = new ObservableCollection<ImageSource>();
        //  public ObservableCollection<ImageSource> ImageList { get; set; } = new ObservableCollection<ImageSource>();
        public ObservableCollection<string> ImageList { get; set; } = new ObservableCollection<string>();
        public List<ChampionInfo> ChampionInfos { get; set; } = new List<ChampionInfo>();
        public DelegateCommand<string> OpenAll { get => new DelegateCommand<string>(OpenallPircture); }

        public bool DataHasLoaded { get; set; }
        #endregion
        public SummonerInfoViewModel(IRegionManager regionManager)
        {
            _regionManager = regionManager;

        }
        private void OpenallPircture(string imageType)
        {
            if (imageType == "Champions")
            {
                DetailWindow detailWindow = new DetailWindow(OwnedChampionsImageAll);
                detailWindow.Show();
            }
            else
            {
                DetailWindow detailWindow = new DetailWindow(OwnedSkinsImageAll);
                detailWindow.Show();
            }

        }
        private void CopyName()//复制数据到粘贴板
        {
            if (!string.IsNullOrEmpty(NickName))
            {
                Clipboard.SetText(NickName);
                Growl.Success("复制成功!");
            }
            else Growl.Warning("复制内容不能为空!");
        }
        //private void MakeFakeData()//造测试数据
        //{
        //    DataList.Clear();
        //    for (int i = 0; i < 20; i++)
        //    {
        //        DataList.Add(new Recordby20 { Hero = "亚索", Outcome = "胜利", GameType = "极地大乱斗", GameTime = DateTime.Now.ToString("G"), CombatGains = i + "" });
        //    }
        //}
        private async Task LoadData()
        {
            if (ProcessFinder.IsPortOpen())
            {
                await LoadBase();
                await LoadResource(Summoner);
            }
        }
        private async Task LoadBase()
        {
            HttpClient LcuClient = new LcuClient()._httpClient;
            var summoner = await GetInfo.GetSummonerAsync(LcuClient);//获取用户名称、等级、头像
            if (summoner == null) Growl.Warning("信息获取失败!请尝试刷新!");
            if (summoner != null)
            {
                Summoner = summoner;
                NickName = summoner.GameName + "#" + summoner.TagLine;
                SummonerLevel = summoner.SummonerLevel.ToString();
                EXP = summoner.XpSinceLastLevel + " / " + summoner.XpUntilNextLevel + " 经验值";
                var imageSource = await GetInfo.GetAvatar(LcuClient, summoner.ProfileIconId);
                if (imageSource != null) Avatar = imageSource;
            }
            if (Summoner != null)
            {
                var rank = await GetInfo.GetRankAsync(LcuClient, Summoner.Puuid);
                Rank = rank;
                //var championInfos = await GetInfo.GetChampionInfos(LcuClient);
                ChampionInfos.Clear();
                ChampionInfos.AddRange(Account.Champions);
                Matches matches = await GetInfo.GetMatchesAsync(LcuClient, Summoner.Puuid, 0, 19);//获取最近20场游戏记录
                var games = matches.games.games;
                DataList.Clear();
                foreach (var game in games)
                {
                    Recordby20 match = new Recordby20();
                    match.GameTime = DateTime.Parse(game.gameCreationDate).ToString("G");
                    match.Outcome = game.participants[0].stats.win ? "胜利" : "失败";
                    match.GameId = game.gameId;
                    var resList = ChampionInfos.Where(item => game.participants[0].championId == item.id).Select(item => new { item.alias, item.name });
                    foreach (var item in resList)
                    {
                        match.Hero = item.name;
                        //var imageSource = await GetInfo.GetChampionsImage(LcuClient, item.squarePortraitPath);
                        match.HeroIcon = string.Format(Base.ChampionIcon, item.alias);
                    }
                    match.GameType = GetGameType(game);
                    match.CombatGains = $"{game.participants[0].stats.kills}/{game.participants[0].stats.deaths}/{game.participants[0].stats.assists}";
                    DataList.Add(match);
                }
                var topThreeHeroes = DataList
                  .GroupBy(r => r.Hero) // 按照 Hero 分组
                  .OrderByDescending(g => g.Count()) // 按出现次数降序排序
                  .Take(3) // 取前3个
                  .Select(g => new
                  {
                      Hero = g.Key,
                      HeroIcon = g.First().HeroIcon // 取第一个记录的 HeroIcon
                  })
                  .ToList();
                ImageList.Clear();
                foreach (var item in topThreeHeroes)
                {
                    ImageList.Add(item.HeroIcon);
                }
            }

        }
        private string GetGameType(MatchGames game)
        {
            switch (game.gameMode)
            {
                case "URF": return "无限火力";
                case "ARURF": return "无限乱斗";
                case "ARAM": return "大乱斗";
                case "CLASSIC":
                    return game.queueId switch
                    {
                        420 => "单双排",
                        430 => "匹配",
                        440 => "灵活排位",
                        _ => "其它"
                    };
                case "ULTBOOK": return "终极魔典";
                default: return "自定义";
            }
        }
        private async Task LoadResource(Summoner summoner)
        {
            HttpClient LcuClient = new LcuClient()._httpClient;
            var ownedChampions = await GetInfo.GetOwnedChampions(LcuClient);//获取拥有英雄图片
            ChampionCount = ownedChampions.Count().ToString();
            if (ownedChampions != null)
            {
                OwnedChampionsImage.Clear();
                OwnedChampionsImageAll.Clear();
                var list = ownedChampions.Reverse();
                foreach (var item in list)
                {
                    var imageSource = await GetInfo.GetChampionsImage(LcuClient, item.BaseLoadScreenPath);
                    if (OwnedChampionsImage.Count <= 8) OwnedChampionsImage.Add(imageSource);
                    OwnedChampionsImageAll.Add(imageSource);
                }
            }
            var ownedSkins = await GetInfo.GetOwnedSkins(LcuClient, summoner.SummonerId);
            var skinIdList = ownedSkins.Where(skin => skin.Ownership.Owned && skin.Id % 1000 != 0).Select(skin => skin.Id);//拿到拥有的皮肤Id
            List<SkinsImageAddress> requestSkinsList = new List<SkinsImageAddress>();
            foreach (var item in skinIdList)
            {
                var address = await GetInfo.GetOwnedSkins(LcuClient, summoner.SummonerId, item / 1000, item);
                requestSkinsList.Add(address);
            }
            SkinsCount = requestSkinsList.Count.ToString();
            OwnedSkinsImage.Clear();
            OwnedSkinsImageAll.Clear();
            foreach (var ob in requestSkinsList)
            {
                var imageSource = await GetInfo.GetChampionsImage(LcuClient, ob.LoadScreenPath);
                if (OwnedSkinsImage.Count <= 8) OwnedSkinsImage.Add(imageSource);
                OwnedSkinsImageAll.Add(imageSource);
            }
        }

        public async void OnNavigatedTo(NavigationContext navigationContext)
        {

            if (navigationContext.Parameters.ContainsKey("shouldReload"))
            {
                bool shouldReload = (bool)navigationContext.Parameters["shouldReload"];
                if (shouldReload)
                {
                    ShowLoading = "Visible";
                    ShowGrid = "Hidden";
                    await LoadData(); // 重新加载数据的方法
                    ShowLoading = "Hidden";
                    ShowGrid = "Visible";
                    DataHasLoaded = true;
                }
            }
            else
            {
                if (!DataHasLoaded)
                {
                    ShowLoading = "Visible";
                    ShowGrid = "Hidden";
                    await LoadData(); // 重新加载数据的方法
                    ShowLoading = "Hidden";
                    ShowGrid = "Visible";
                    DataHasLoaded = true;
                }
            }
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            return;
        }

    }
}
